/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package databaseserver;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author ntfsbk
 */
public class ManageUserThread extends Thread {

    private JTable table;
    private boolean running = true;

    public ManageUserThread() {
    }

    public ManageUserThread(JTable talble) {
        this.table = talble;
    }

    public boolean isRunning() {
        return running;
    }

    public void setRunning(boolean running) {
        this.running = running;
    }

    @Override
    public void run() {
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            String connectionUrl = "jdbc:sqlserver://localhost:1433;"
                    + "databaseName=sharing;userName=sa;password=123456";
            
            while(true){
                if(isRunning()){
                    Connection conn = DriverManager.getConnection(connectionUrl);
                    Statement statement = conn.createStatement();
                    String sqlQuery="select * from users where available=1";
                    ResultSet rs=statement.executeQuery(sqlQuery);
                    int i=0;
                    DefaultTableModel model=(DefaultTableModel) table.getModel();
                    model.setRowCount(0);
                    while(rs.next()){
                        i++;
                        String userName=rs.getString("userId");
                        String ip=rs.getString("userAddress");
                        int port =rs.getInt("port");
                        model.addRow(new Object[]{
                            i,userName,ip,port
                        });
                    }
                    Thread.currentThread().sleep(3000);
                }
                else
                    return;
            }
        } catch (Exception e) {
            System.out.println("run in ManageUserThread");
            e.printStackTrace();
        }

    }
}
